// packageA/pages/complaintList/complaintList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词
    searchValue:'',
    //状态筛选
    optionState:[
      {text: '所有状态', value: -1},
      {text: '待派单', value: 0},
      {text: '待处理', value: 2},
			{text: '待验收', value: 3},
			{text: '已完成', value: 1}
    ],
		valueState: -1,
    //登录用户
    user: null,
    //开始时间
    startTime: '开始日期',
    //开始时间选择框
    showStartTime:false,
    //结束时间
    endTime: '结束日期',
    //结束时间选择框
    showEndTime:false,
    //当前时间
    currentStart: new Date().getTime(),
    currentEnd: new Date().getTime(),
    //最小时间
    minDate2:null,
    //最大时间
    maxDate1: new Date().getTime(),
    maxDate2: new Date().getTime(),
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } 
      return value
		},
		//查询条件，项目id
		queryProjectIds: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;
    if(user){
      this.setData({
        user: user
			})
			
			//投诉工单列表
			this.getList();
			 
    }else{
			//跳转登录
			wx.redirectTo({
				url: "/pages/login/login?from=quit"
			})
    }
	},	

  //获取列表数据
  getList(){
		let dataObj={
			selectFields: ['id','place','state','project','createDate','dispatchUser','handler','createUser','type','handler','handleTime','problem'],
			sort: {
				id: -1
			},
			page: {
				page: this.data.page,
				pageSize: 10
			}
		}

    //筛选状态
    if(this.data.valueState!=-1){
      dataObj.state=this.data.valueState;
		}

    //模糊查询
    if(this.data.searchValue){
      dataObj['project.name']='%' +this.data.searchValue+ '%';
    }

    //创建时间
    if(this.data.startTime!='开始日期' && this.data.endTime!='结束日期'){
      dataObj.complex=[{
        and: {
          createDate: {
            ">=": this.data.startTime + " 00:00:00",
            "<=": this.data.endTime + " 23:59:59"
          }
        }
      }]  
		}

		//投诉工单用户只能查自己创建的
		let user = this.data.user;
		if(user.role.indexOf(132)!=-1){
			dataObj['createUser.id'] = user.id;
		}
		
		let param = {
			isAuth: true,
			//表名complaint_order
      className: 'complaintOrder',
      data: dataObj
		}

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        result.forEach(item => {
          //状态
          switch(item.state){
            case 0:
              item.self_state='待派单';
              item.self_stateClass='c-0';
              break;
            case 1:
              item.self_state='已完成';
              item.self_stateClass='c-1';
              break;
            case 2:
              item.self_state='待处理';
              item.self_stateClass='c-2';
							break;
						case 3:
              item.self_state='待验收';
              item.self_stateClass='c-3';
              break;
          }

          //（投诉时间）创建时间
          if(item.createDate){
            item.self_createDate = util.timeFormat(item.createDate);
					}
					
					//处理时间
					if(item.handleTime){
						item.self_handleTime = util.timeFormat(item.handleTime);
					}
        });

        console.log('投诉工单列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
        Toast.clear();
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
          Toast.clear();
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
      Toast.clear();
    })
	},
	
	//无数据
	notDatas(){
		this.setData({
			showNothing: true
		})
		Toast.clear();
	},

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value.trim(),
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //跳转添加
  goToAdd(){
    wx.navigateTo({
      url: "/pages/complaintAdd/complaintAdd"
    })
  },

  //跳转编辑
  goToEdit(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      id: detail.id
    }
    wx.navigateTo({
      url: "/packageA/pages/cleanWorkAdd/cleanWorkAdd?paramObj="+JSON.stringify(obj)
    })
  },

  //跳转详情
  goToLook(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      id: detail.id
    }
    wx.navigateTo({
      url: "/packageA/pages/complaintDetail/complaintDetail?paramObj="+JSON.stringify(obj)
    })
  },

  //跳转处理
  goToHandle(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      id: detail.id
    }
    wx.navigateTo({
      url: "/packageA/pages/complaintHandle/complaintHandle?paramObj="+JSON.stringify(obj)
    })
  },

  //删除
  onDelete(e){
    Dialog.confirm({
      title: '确定删除此工单吗',
      confirmButtonText:'确定',
      cancelButtonText:'不删除了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        className:"complaintOrder",
        data:{
          id:detail.id
        }
      }

      CommonService.goDelete(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已删除');
          //刷新列表和页码
          this.refreshListAndPage();
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },

  //预览图片
  onPreviewImage(e) {
    let detail = e.target.dataset.detail;
    let src = e.target.dataset.src;

    let newArr=[];
    for(let i=0;i<detail.length;i++){
      newArr.push(detail[i].url);
    }

    wx.previewImage({
      current: src,
      urls: newArr
    })
  },

  //选择状态
  onChangeState({detail}) {
    this.setData({
      valueState: detail
    })
    this.refreshListAndPage();
	},

  //接单
  onStart(e){
    Dialog.confirm({
      title: '确定接单吗',
      confirmButtonText:'确定',
      cancelButtonText:'取消'
    }).then(() => {

			let detail=e.currentTarget.dataset.detail;
			let obj={
				id: detail.id,
				//是否接单（为了区分编辑）
				isReceive: true
			}
			wx.navigateTo({
				url: "/packageA/pages/cleanWorkAdd/cleanWorkAdd?paramObj="+JSON.stringify(obj)
			})
    }).catch(() => {
    });
  },

  //显示开始时间
  onShowStartTime(){
    this.setData({
			showStartTime: true
    })
  },

  //隐藏开始时间
  onCloseStartTime(){
    this.setData({
			showStartTime: false
    })
  },

  //确认开始时间
  onConfirmStartTime(e) {
    this.setData({
      currentStart: e.detail,
      minDate2:e.detail,
      startTime:util.timeFormatDay(e.detail),
    })
    this.onCloseStartTime();

    if(this.data.endTime!='结束日期'){
      this.refreshListAndPage();
    }  
  },

  //显示结束时间
  onShowEndTime(){
    this.setData({
			showEndTime: true
    })
  },

  //隐藏结束时间
  onCloseEndTime(){
    this.setData({
			showEndTime: false
    })
  },

  //确认结束时间
  onConfirmEndTime(e) {
    this.setData({
      currentEnd: e.detail,
      maxDate1:e.detail,
      endTime:util.timeFormatDay(e.detail),
    })
    this.onCloseEndTime();

    if(this.data.startTime!='开始日期'){
      this.refreshListAndPage();
    }
  },

  //清除时间
  onCancelTime(){
    this.setData({
      startTime: '开始日期',
      endTime: '结束日期'
    })
    
    this.onCloseStartTime();
    this.onCloseEndTime();
    this.refreshListAndPage();
	},

	//跳转派单
	goToDispatch({currentTarget}){
		let detail = currentTarget.dataset.detail;
    let obj={
      id: detail.id
    }
    wx.navigateTo({
      url: "/packageA/pages/complaintDispatch/complaintDispatch?paramObj="+JSON.stringify(obj)
    })
	},
	
	//跳转验收评价
  goToCheck({currentTarget}){
    let detail=currentTarget.dataset.detail;
    let obj={
      id: detail.id
    }
    wx.navigateTo({
      url: "/packageA/pages/complaintCheck/complaintCheck?paramObj="+JSON.stringify(obj)
    })
	},	

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})